package com.googlecode.lookie.preview;

import javax.swing.event.EventListenerList;

public class DefaultImagePreviewModel
    implements ImagePreviewModel
{

    private EventListenerList listenerList = new EventListenerList();

    private ImageSource imageSource;

    public DefaultImagePreviewModel()
    {
    }

    public DefaultImagePreviewModel( ImageSource imageSource )
    {
        this.imageSource = imageSource;
    }

    public void addListener( ImagePreviewModelListener listener )
    {
        listenerList.add( ImagePreviewModelListener.class, listener );
    }

    public void removeListener( ImagePreviewModelListener listener )
    {
        listenerList.remove( ImagePreviewModelListener.class, listener );
    }

    protected void fireImageChanged( Object source )
    {
        Object[] listeners = listenerList.getListenerList();
        ImageChangedEvent e = null;

        for ( int i = listeners.length - 2; i >= 0; i -= 2 )
        {
            if ( listeners[i] == ImagePreviewModelListener.class )
            {
                if ( e == null )
                {
                    e = new ImageChangedEvent( source );
                }
                ( (ImagePreviewModelListener) listeners[i + 1] ).imageChanged( e );
            }
        }
    }

    public ImageSource getImageSource()
    {
        return imageSource;
    }

    public void setImageSource( ImageSource imageSource )
    {
        this.imageSource = imageSource;
        fireImageChanged( this );
    }

}
